<template>
  <div>
       <!--导入按钮 -->
    <el-button type="primary" @click="importData">
      <i class="fa fa-plus" />{{ $t('common.import') }}
    </el-button>
     <!-- 导出按钮 -->

     <el-button type="primary" @click="exportData" style="margin-left:10px"
            > {{ $t('common.export') }}</el-button
          >

    <!-- 添加-------------------------------- -->
    <div align="right">
      <el-button type="success" @click="addTopic" icon="el-icon-plus"
        >{{$t('common.add')}}</el-button
      >
    </div>
     <!-- 批量删除 -->
    <div>
      <el-button type="danger" size="mini" @click="removeRows()">{{ $t('common.bulkDelete') }}</el-button>
    </div>
    <!-- --------------------------------------列表页 -->
    <el-table :data="list" border fit highlight-current-row  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column :label="$t('topiclist.table.choiceId')" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.choiceId }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('topiclist.table.type')" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('topiclist.table.question')" >
        <template slot-scope="scope">
          {{ scope.row.question }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('topiclist.table.choicea')" >
        <template slot-scope="scope">
          <span>A.{{ scope.row.choicea }}</span>
          <tr>
            B.{{
              scope.row.choiceb
            }}
          </tr>
          <tr>
            C.{{
              scope.row.choicec
            }}
          </tr>
          <tr>
            D.{{
              scope.row.choiced
            }}
          </tr>
        </template>
      </el-table-column>

      <el-table-column :label="$t('topiclist.table.rightAnswer')" >
        <template slot-scope="scope">
          <p style="color: #039e2a">
            <span v-if="scope.row.rightAnswer == 1"
              >A.{{ scope.row.choicea }}</span
            >
            <span v-if="scope.row.rightAnswer == 2"
              >B.{{ scope.row.choiceb }}</span
            >
            <span v-if="scope.row.rightAnswer == 3"
              >C.{{ scope.row.choicec }}</span
            >
            <span v-if="scope.row.rightAnswer == 4"
              >D.{{ scope.row.choiced }}</span
            >
          </p>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('common.operate')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editTopic(row)"
          >
            {{ $t('common.update') }}
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="delTopic(row)"
          >
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
     <!-- 导入 -->
    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
            <el-upload
              :action="'http://42.194.159.131:8080/article/batchAddChoice'"
              :on-success="onUploadSuccess"
              :multiple="false"
              class="upload-demo"
              >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible=false">取消</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------- -->
    <!-- ----------------------------------分页 -->
    <div class="block" style="float: right; margin-top: 20px">
      <!-- <span class="demonstration">显示总数</span> -->
      <el-pagination
        background
        @current-change="fetchData"
        :current-page.sync="page_num"
        :page-size="page_size"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- ---------------------------------------对话框-->
    <el-dialog
      :title="Topic.choiceId ? '修改题目信息' : '添加题目信息'"
      :visible.sync="dialogFormVisible"
    >
      <!-- form表单验证------------------------- -->
      <el-form style="width: 80%" :model="Topic" :rules="rules" ref="ruleForm">
        <el-form-item label="题目" label-width="100px" prop="question">
          <el-input autocomplete="off" v-model="Topic.question"  placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="题目类型" label-width="100px" prop="type">
          <!-- <el-input autocomplete="off" v-model="Topic.type"  placeholder="请输入内容"></el-input> -->
          <el-select v-model="Topic.type" placeholder="请选择题目类型">
          <el-option label="健康养生" value="健康养生"></el-option>
          <el-option label="健康考试" value="健康考试"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
        <el-button
          type="success"
          @click="addType"
          icon="el-icon-plus"
        ></el-button>
        </el-form-item>
        <el-form-item label="题目选项" label-width="100px" prop="choicea">
          A.<el-input autocomplete="off" v-model="Topic.choicea"   placeholder="请输入答案A"></el-input>
        </el-form-item>
         <el-form-item  label-width="100px" prop="choiceb">
         B.<el-input autocomplete="off" v-model="Topic.choiceb"   placeholder="请输入答案B"></el-input>
         </el-form-item>
          <el-form-item  label-width="100px" prop="choicec">
         C.<el-input autocomplete="off" v-model="Topic.choicec"   placeholder="请输入答案C"></el-input>
         </el-form-item>
          <el-form-item  label-width="100px" prop="choiced">
         D.<el-input autocomplete="off" v-model="Topic.choiced"   placeholder="请输入答案D"></el-input>
         </el-form-item>
        <el-form-item label="正确答案" label-width="100px" prop="rightAnswer">
          <el-input autocomplete="off" v-model.number="Topic.rightAnswer"  placeholder="请输入正确答案1，2，3，4（分别代表A,B,C,D）"></el-input>
        </el-form-item>
        <el-form-item label="发布时间" label-width="100px" prop="createTime">
          <el-date-picker
          v-model="Topic.createTime"
          type="datetime"
          placeholder="选择日期时间"
          value-format="timestamp"
        >
        </el-date-picker>
        </el-form-item>
        <el-form-item label="中止时间" label-width="100px" prop="updateTime">
          <el-date-picker
          v-model="Topic.updateTime"
          type="datetime"
          placeholder="选择日期时间"
          value-format="timestamp"
        >
        </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addorupdateTopic">确 定</el-button>
      </div>
    </el-dialog>

     <el-dialog :visible.sync="dialogFormVisibles">
      <el-form style="width: 80%" :model="Topic" >
        <el-form-item label="题目类型" label-width="100px">
          <el-input autocomplete="off" v-model="Topic.type"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisibles = false">添 加</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------- -->
    <!-- --------------------------------------- -->
  </div>
</template>
<script>
import healtopic from "@/api/healthyarticle";
export default {
  //定义变量和初始值
  data() {
    //正确答案判断
      var checkanswer = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('答案不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value >4) {
              callback(new Error('正确答案应该为1，2，3，4其中一个'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
    return {
      dialogFormVisibles: false, //对话框（查看）
      // -------------------------------------------日历
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      list: {}, //每页数据集合
      multipleSelection: [], //批量选择中选择的记录列表
      page_num: 1,
      page_size: 8, //每8个数据一页
      total: 1, //初始化
       dialogImportVisible:false,//弹框
      dialogFormVisible: false, //对话框（查看）
      Topic: {
        question: "",
        type: "",
        updateTime:'',
        createTime:''
      },
      //表单验证规则
      rules: {

        question: [
          { required: true, message: "请输入问题", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
         type: [
            { required: true, message: '请输入类型', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
          ],
          choicea: [
            { required: true, message: '请输入答案', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
          choiceb: [
            { required: true, message: '请输入答案', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
          choicec: [
            { required: true, message: '请输入答案', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
          choiced: [
            { required: true, message: '请输入答案', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
          rightAnswer:[
           { validator: checkanswer, trigger: 'blur' }
          ],
           createTime: [
            { type: 'number', required: true, message: '请选择发布日期、时间', trigger: 'blur' },
          ],
          updateTime: [
            { type: 'number', required: true, message: '请选择中止日期、时间', trigger: 'blur' },
          ],
      },
    };
  },

  //在页面渲染前执行
  //调用methods定义的方法，得到数据

  created() {
    this.fetchData();
  },
  methods: {
     //导入数据字典
    importData(){
      this.dialogImportVisible = true
    },
     //上传成功调用
    onUploadSuccess(){
        this.dialogImportVisible = false
        this.fetchData(1);
        this.$message({
        	  message: '导入数据成功!',
        	  type: 'success'
          })
    },
     //导出数据字典
    exportData(){
      window.location.href="http://42.194.159.131:8080/article/exportChoiceData"
    },
     //获取选择复选框的id值
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
      //批量删除
    removeRows(){
         this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //遍历数组得到每个id值，设置到idList里面
          var idList = []
          for(var i =0;i< this.multipleSelection.length;i++){
            var obj =  this.multipleSelection[i];
            var id = obj.choiceId
            idList.push(id)
          }
          //调用接口
          healtopic.batchRemoveChoice(idList).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            console.log('aaaaaaaaaa',resp.message);
            //刷新页面数据
            this.fetchData(1);
          })
          .catch(()=>{
          
          this.$message({
            type: "error",
            message: "删除失败!权限不足，请联系管理员进行升级",
          });
        
       })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addTopic() {
      this.dialogFormVisible = true;
      //清除一下数组
      this.Topic = {
        createTime: "2022-04-29T02:21:48.784Z",
        question: "",
        type: "",
        updateTime: "2022-04-29T02:21:48.784Z",
      };
    },
    //修改问题
    editTopic(row) {
      console.log(row);
      this.dialogFormVisible = true;
      this.Topic = { ...row };
    },
    //页面列表页渲染，请求接口调用
    fetchData(page = 1) {
      this.page_num = page;
      var vm = this;
      healtopic
        .getHealthytopicList(this.page_num, this.page_size)
        //请求成功调用
        .then(function (res) {
          vm.list = res.data.choices;
          vm.total = res.data.total;
        });
    },
    //添加或者修改确定按钮
    addorupdateTopic() {
      // debugger
      console.log(this.Topic)
      if (!this.Topic.createTime) return this.$message.error('请选择发布时间');
      if (!this.Topic.updateTime) return this.$message.error('请选择中止时间');
      //获取from结点，验证字段
      this.$refs.ruleForm.validate(async (success) => {
        console.log(success)
        //如果全部字段符合条件
        if (success) {
          this.dialogFormVisible = false;
          let result = await healtopic.reqAddOrUpdateTopic(this.Topic);
          console.log('aaaaaaaaaaaaaaaaaa',result);
          if(result.errorCode ==0){
             this.$message({
            type: "success",
            message: this.Topic.choiceId ? "修改问题成功" : "添加问题成功",
          });
          this.fetchData(this.Topic.choiceId ? this.page_num : 1); // 更新商品列表
          }

          console.log("qqqqqqqqqqqqqqqqqqq", result.data);
        } else {
          console.log(success)
          console.log(success)
          console.log(success)
          console.log(success)
          return false;
        }
      });
    },
    addType(){
    console.log('aaaaaaa');
    this.dialogFormVisibles = true;
  },
    delTopic(row) {
      this.$confirm("此操作将永久删除该题目信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          healtopic.deltopic(row.choiceId).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面数据
            this.fetchData(1);
          })
          .catch(()=>{
          
          this.$message({
            type: "error",
            message: "删除失败!权限不足，请联系管理员进行升级",
          });
        
       })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="less" >
</style>
